{extend name="../../base/view/common/base" /}
{block name="style"}
<style>
    .form-group {
        margin-bottom: 15px;
    }
    .form-control {
        width: 100%;
        padding: 6px 12px;
        font-size: 14px;
        line-height: 1.42857143;
        color: #555;
        background-color: #fff;
        background-image: none;
        border: 1px solid #ccc;
        border-radius: 4px;
        box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
        transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;
    }
    .layui-form-label {
        width: 120px;
    }
    .layui-input-block {
        margin-left: 140px;
        display: flex;
        align-items: flex-start;
        flex-wrap: wrap;
    }
    .layui-input-inline {
        margin-right: 10px;
        width: 150px;
    }
</style>
{/block}
<!-- 主体 -->
{block name="body"}
<div class="layui-form p-page">
    <h3 class="pb-3">{$id ? '编辑' : '添加'}当事人</h3>
    <form class="layui-form" id="partyForm">
        <input type="hidden" name="id" value="{$detail.id|default=''}">
        <div class="layui-form-item">
            <label class="layui-form-label">当事人名称</label>
            <div class="layui-input-block">
                <input type="text" name="name" value="{$detail.name|default=''}" required lay-verify="required" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">类型</label>
            <div class="layui-input-block">
                <input type="radio" name="party_type" lay-filter="type" value="1" title="个人" {if condition="$detail.party_type eq 1"}checked{/if}>
                <input type="radio" name="party_type" lay-filter="type" value="2" title="企业" {if condition="$detail.party_type eq 2"}checked{/if}>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">证件号码</label>
            <div class="layui-input-block">
                <input type="text" name="id_number" value="{$detail.id_number|default=''}"  autocomplete="off" class="layui-input" placeholder="请输入证件号码" id="idNumberInput">
            </div>
        </div>
        <div class="layui-form-item party-qiye">
            <label class="layui-form-label">法人</label>
            <div class="layui-input-block">
                <input type="text" name="legal_representative" value="{$detail.legal_representative|default=''}" autocomplete="off" class="layui-input" placeholder="请输入法人姓名">
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label">联系人</label>
                <div class="layui-input-inline">
                    <input type="text" name="contact" value="{$detail.contact|default=''}" autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label">联系电话</label>
                <div class="layui-input-inline">
                    <input type="text" name="phone" value="{$detail.phone|default=''}" autocomplete="off" class="layui-input">
                </div>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">联系地址</label>
            <div class="layui-input-block">
                <div class="layui-form-item" style="margin-bottom: 10px;">
                    <div class="layui-input-inline">
                        <select name="pid" lay-filter="pid" lay-reqText="请选择省份" data-value='{$detail.pid|default=""}'>
                            <option value="">请选择省份</option>
                        </select>
                    </div>
                    <div class="layui-input-inline">
                        <select name="cid" lay-filter="cid"  lay-reqText="请选择城市" data-value='{$detail.cid|default=""}'>
                            <option value="">请选择城市</option>
                        </select>
                    </div>
                    <div class="layui-input-inline">
                        <select name="did" lay-filter="did" lay-reqText="请选择区县" data-value='{$detail.did|default=""}'>
                            <option value="">请选择区/县</option>
                        </select>
                    </div>
                </div>
                <input type="text" name="address" value="{$detail.address|default=''}" autocomplete="off" lay-reqText="请输入详细地址" placeholder="请输入详细地址" class="layui-input">
            </div>
        </div>

        <div class="layui-form-item">
            <div class="layui-input-block">
                <button class="layui-btn" lay-submit lay-filter="formDemo">立即提交</button>
                <button type="reset" class="layui-btn layui-btn-primary">重置</button>
            </div>
        </div>
    </form>
</div>
{/block}

<!-- 脚本 -->
{block name="script"}
<script>
function gouguInit() {
    layui.use(['form', 'layer', 'jquery', 'laydate'], function() {
        var form = layui.form,
            layer = layui.layer,
            $ = layui.jquery,
            laydate = layui.laydate;

        // 渲染表单
        form.render();
        
        // 确保radio控件已渲染后再绑定事件
        form.render('radio');
        
        // 监听party_type变化
        form.on('radio(type)', function(data){
            if(data.value==2){
                $('.party-qiye').show();
                $('#idNumberInput').attr('placeholder', '请输入统一社会信用代码');
            }else{
                $('.party-qiye').hide();
                $('#idNumberInput').attr('placeholder', '请输入身份证号码');
            }
        });
        
        // 初始化时根据当前选中值设置状态
        var initType = $('input[name="party_type"]:checked').val();
        if(initType == 2) {
            $('.party-qiye').show();
            $('#idNumberInput').attr('placeholder', '请输入统一社会信用代码');
        } else {
            $('.party-qiye').hide();
            $('#idNumberInput').attr('placeholder', '请输入身份证号码');
        }

        // 监听地址省份选择变化
        form.on('select(pid)', function(data) {
            var provinceId = data.value;
            if (provinceId) {
                // 加载城市选项
                loadRegionOptions('cid', '/home/api/regionCitys', { provinceId: provinceId });
                // 清空区县选择
                $('select[name="did"]').html('<option value="">请选择区/县</option>');
            } else {
                $('select[name="cid"]').html('<option value="">请选择城市</option>');
                $('select[name="did"]').html('<option value="">请选择区/县</option>');
                form.render();
            }
        });

        // 监听地址城市选择变化
        form.on('select(cid)', function(data) {
            var cityId = data.value;
            if (cityId) {
                // 加载区/县选项
                loadRegionOptions('did', '/home/api/regionDists', { cityId: cityId });
            } else {
                $('select[name="did"]').html('<option value="">请选择区/县</option>');
                form.render();
            }
        });

        // 表单提交
        form.on('submit(formDemo)', function(data){
            var loading = layer.load(2);
            $.post('/lawcase/party/add', data.field, function(res){
                layer.close(loading);
                if(res.code === 0){
                    // 判断是否来自案件详情页
                    if(window.opener && typeof window.opener.partyInit === 'function'){
                        // 调用关联方法
                        window.opener.tool.post('/lawcase/api/link_party_case', {
                            case_id: window.opener.$('#case_id').val(),
                            party_id: res.data.id
                        }, function(res){
                            if(res.code === 0){
                                layer.msg('添加并关联成功');
                                window.opener.table.reload('partyTable');
                                setTimeout(function(){
                                    window.close();
                                }, 1500);
                            } else {
                                layer.msg(res.msg);
                            }
                        });
                    } else {
                        layer.msg('添加成功');
                        setTimeout(function(){
                            window.close();
                        }, 1500);
                    }
                } else {
                    layer.msg(res.msg);
                }
            });
            return false;
        });

        // 加载地区选项数据
        function loadRegionOptions(selectName, url, params = {}) {
            // 显示加载中状态
            let $select = $(`select[name="${selectName}"]`);
            $select.html('<option value="">加载中...</option>');
            form.render('select');

            // 使用jQuery的AJAX请求
            $.get(url, params)
               .done(function(data) {
                    if (data && data.data && Array.isArray(data.data)) {
                        var redata = data.data;
                        var html = '<option value="">请选择省份</option>';
                        for (var i = 0; i < redata.length; i++) {
                            var selected = params.selectedId && redata[i].id == params.selectedId ? 'selected' : '';
                            html += `<option value="${redata[i].id}" ${selected}>${redata[i].name}</option>`;
                        }
                        $select.html(html);
                    } else {
                        $select.html('<option value="">加载失败</option>');
                        layer.msg('加载地区数据失败');
                    }
                    form.render('select');
                })
               .fail(function(jqXHR, textStatus, errorThrown) {
                    $select.html('<option value="">加载失败</option>');
                    layer.msg(`加载地区选项失败: ${textStatus}`);
                    form.render('select');
                });
        }

        // 如果是编辑模式，预加载地区数据
        var isEditMode = '{$id}' != '0';
        var provinceId = isEditMode ? '{$detail.pid}' : '';
        var cityId = isEditMode ? '{$detail.cid}' : '';
        var distId = isEditMode ? '{$detail.did}' : '';

        // 初始化省份数据
        loadRegionOptions('pid', '/home/api/regionProvinces', { 
            selectedId: $('select[name="pid"]').data('value') || provinceId 
        });

        // 如果是编辑模式，预加载城市数据
        if (provinceId) {
            loadRegionOptions('cid', '/home/api/regionCitys', { 
                provinceId: provinceId, 
                selectedId: $('select[name="cid"]').data('value') || cityId 
            });
        }

        // 如果是编辑模式，预加载区县数据
        if (cityId) {
            loadRegionOptions('did', '/home/api/regionDists', { 
                cityId: cityId, 
                selectedId: $('select[name="did"]').data('value') || distId 
            });
        }

        // 监听提交
        form.on('submit(formDemo)', function(data){
            layer.confirm('确定提交吗？', {
                icon: 3,
                title: '提示'
            }, function(index){
                layer.close(index);
                var loadIndex = layer.load(2, {shade: [0.1, '#fff']});
                $.post('/lawcase/party/add', data.field, function(res){
                    layer.close(loadIndex);
                    if(res.code === 0){
                        layer.msg(res.msg || "{$id ? '编辑成功' : '添加成功'}", {
                            icon: 1,
                            time: 1000
                        }, function(){
                            parent.layer.close(parent.layer.getFrameIndex(window.name));
                            // 调用父页面的partyInit方法刷新当事人列表
                            parent.partyInit(); 
                        });
                    } else {
                        layer.msg(res.msg || "{$id ? '编辑失败' : '添加失败'}", {
                            icon: 2,
                            time: 2000
                        });
                    }
                });
            });
            return false;
        });
    });
}
</script>
{/block}
